﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using EuroManager.Domain.Simulator.Engine;
using EuroManager.Domain.Simulator.Helpers;
using EuroManager.Domain.Simulator.World;

namespace EuroManager.Domain.Simulator.AI
{
    public class TeamAI : ITeamAI
    {
        private static readonly float decisionDelay = 0.5f;

        private ITeam team;
        private IRandomizer random;
        private Timer decisionTimer;

        public TeamAI(ITeam team, IRandomizer random)
        {
            Contract.Requires(team != null);
            Contract.Requires(random != null);

            this.team = team;
            this.random = random;

            decisionTimer = new Timer(decisionDelay);
        }

        public void Update(float elapsedTime)
        {
            decisionTimer.Update(elapsedTime);

            if (decisionTimer.HasPassed)
            {
                decisionTimer.Reset(random.PlayerAIDecisionDelaySalt(decisionDelay));

                if (!team.HasBall)
                {
                    SelectPlayersToChaseBall();
                }
            }
        }

        private void SelectPlayersToChaseBall()
        {
            float bestTime = Single.MaxValue;
            IPlayer interceptor = null;

            foreach (IPlayer player in team.Players)
            {
                if (player.TimeToReachBall < bestTime)
                {
                    bestTime = player.TimeToReachBall;
                    interceptor = player;
                }
            }

            if (interceptor != null)
            {
                interceptor.ChaseBall();
            }

            foreach (IPlayer player in team.Players.Where(p => p != interceptor))
            {
                player.Observe();
            }
        }
    }
}
